package com.example.demo.service;

import com.example.demo.dao.TableMapper;
import com.example.demo.entity.TableEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.core.ApplicationContext;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @ClassName TransactionServiceA
 * @Author bsy
 * @Description TODO
 * @Date 2022/8/25 21:58
 * @Version 1.0
 */
@Service
@Slf4j
public class TransactionServiceA {

    @Autowired
    private TableMapper tableMapper;

    @Autowired
    private TransactionServiceB transactionServiceB;

    @Transactional
    public void methodA() throws Exception {
        tableMapper.insertTableA(new TableEntity());

        try {
            transactionServiceB.methodB();
        } catch (Exception e) {

        }
        //使用该类内部方法
        //this.nestMethod();
        //AopContext 实现代理
        //((TransactionServiceA)AopContext.currentProxy()).nestMethod();

        //多线程下的事务失效问题
//        new Thread(()->{
//            transactionServiceB.methodB();
//        }).start();

//        try {
//            transactionServiceB.methodB();
//        } catch (Exception e) {
//            log.error("methodA 捕获异常：{}", e.fillInStackTrace());
//        }

       // throw new RuntimeException();
    }


    @Transactional(rollbackFor = Exception.class)
    public void nestMethod(){
        tableMapper.insertTableB(new TableEntity());
        throw new RuntimeException();
    }
}